// pages/my/orderDetail/orderDetail.js
import moment from '../../../utils/moment.js'
var app = getApp()
Page({
  data: {
    goodsInfoShow: true,
    goodsPriceShow: false,
    showToast:false,
    showToastTit:'',
    showToastImg:'',
    blackPrice:true,
    logisticsList: [],
    addressInfo: {
      title:"收货人",
      name: "",
      phone: "",
      address: ""
    },
    orderDetail: {},
    saler:'',
    isPay:'',
    accountId:'',
    company:'',
    expressNo:'',
    voucher:false,
    isCompany:true,
    isScanCode:false,
    payCode:'',
    nickName:'',
    avatarUrl:''
  },
  onLoad: function(options) {
    console.log(options)

    wx.setNavigationBarTitle({
      title: options.title,
    })
    app.getMemInfo().then(res=>{
      this.setData({
        accountId:res.data.id
      })
    })
    this.setData({
      orderType: options.type,
      orderId:options.orderId,
      isPay:options.pay?options.pay:'',
      saler:options.saler?options.saler:'',
      expressNo:options.expressNo,
      companyName:options.companyName,
      logo:options.logo,
      color:options.color,
      company:options.company
    })
    if (options.type==0) {
      this.monitorVoucher(options.orderId)
      if (options.pay==0) {
        this.getPayCode(options.orderId)
      }
    }
    var orderDetail = this.data.orderDetail;
    orderDetail["orderStatus"] = options.type;
    if (options.type!=0){
      this.setData({
        orderDetail: orderDetail,
        goodsPriceShow: false,
        blackPrice: true,
      })
      this.getDetailByState(options.orderId,options.color,options.companyName)
    }else{
      this.setData({
        goodsPriceShow: true,
        blackPrice: false,
      })
      this.getCusDetail(options.orderId,options.color,options.company)
    }

  },
 //配送详情
 logisticsMoretap:function(){
  let logisticsType = this.data.orderDetail.logisticsType
  let company = this.data.company
  let expressNo = this.data.expressNo
  if (logisticsType=='第三方物流') {
    wx.navigateTo({
      url: '../logistics/logistics?orderId='+this.data.orderId+'&logisticType="第三方物流"',
    })
  }else if (logisticsType=='卖家配送') {
    wx.navigateTo({
      url: '../logistics/logistics?orderId='+this.data.orderId+'&logisticType="卖家配送"',
    })
  }else{
    wx.navigateTo({
      url: '../logistics/logistics?orderId='+this.data.orderId+'&logisticType="自提"',
    })
  }

},
  //删除订单
  deleteOrderTap(){
    let data = {
      orderId:this.data.orderId,
      accountId:this.data.accountId
    }
    console.log(data)
    wx.showModal({
      title: '删除订单',
      content: '确定要删除订单吗?',
      cancelColor:"#333333",
      confirmColor: "#539FFF",
      success: function (res) {
        if (res.confirm) {
          app.request('wx_app/user_order/del',data,'GET').then(res=>{
            console.log(res)
            if (res.code==1) {
              wx.showToast({
                title:'删除成功',
                success(){
                  // setTimeout(function(){
                  //   wx.redirectTo({
                  //     url:'../orders/orders?title=客户订单&orderType=' + 0,
                  //   })
                  // },1000)
                  setTimeout(function(){
                    wx.switchTab({
                      url:'../my',
                    })
                  },1000)
                }
              })
            }else{
              app.errorMsg(res.message)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //申请退款
  applyRefundTap:function(e){
    let index = e.currentTarget.dataset.index
    let data = {
      orderId:this.data.orderId,
      orderNo:this.data.orderDetail.orderNo,
      manufacturerId:this.data.orderDetail.manufacturerId,
      productDetail:this.data.orderDetail.goodsList[index]
    }
    console.log(data)
    let productInfo = JSON.stringify(data)
    console.log(productInfo)
    wx.navigateTo({
      url: '../applyRefund/applyRefund?info='+productInfo
    })
  },
  //催单
  reminderTap:function(e){
    var that = this
    let time = this.data.orderDetail.downTime
    console.log(time)
    let begin = moment(time).add(3,'d')
    console.log(begin)
    let now = moment()
    if (moment().isAfter(begin)) {  //三天后
      console.log(123)
      let data = {
        orderId:this.data.orderId
      }
      console.log(data)
      app.request('wx_app/agent_order/sendReminder',data,'GET').then(res=>{
        console.log(res)
        if (res.code==1) {
          this.setData({
            showToast:true,
            showToastTit:'已催促厂家发货',
            showToastImg:'../../../image/success.png'
          })
          setTimeout(function(){
            that.setData({
              showToast:false
            })
          },1500)
        }else{
          app.errorMsg(res.message)
        }
      })
    }else{  //没到三天
      console.log(321)
      this.setData({
        showToast:true,
        showToastTit:'下单后3日才可催单',
        showToastImg:'../../../image/wrong.png'
      })
      setTimeout(function(){
        that.setData({
          showToast:false
        })
      },1500)
    }
  },
  orderDetailTap:function(e){
    var id = e.currentTarget.dataset.goodId;
    var type = e.currentTarget.dataset.type;
    if (this.data.orderType>0) {
      wx.navigateTo({
        url: '../../my/purchase/purchaseDetail?id='+id+'&goodsType='+type,
      })
    }else{
      // wx.navigateTo({
      //   url: '../../stock/goodsDetail?id='+id+'&goodsType='+type+'&mark=1',
      // })
    }
  },
  //客户订单详情
  getCusDetail(orderId){
    let data = {
      orderId
    }
    console.log(data)
    let goodsList = []
    app.request('wx_app/user_order/detail',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        res.data.orderDetails.forEach(item=>{
          goodsList.push({
            name:item.name,
            url: item.pic,
            num: item.amount,
            price: item.price,
            type: item.des,
            productId:item.productId,
            productType:item.productType,
            actualPrice:item.actualPrice,
            color:item.tagColor,
            companyName:item.productTag,
            isDeleted:item.isDeleted
          })
        })
        this.setData({
          ['orderDetail.goodsPrice']:res.data.orderPrice,
          ['orderDetail.orderNo']:res.data.orderNo,
          ['orderDetail.downTime']:res.data.createTime.split('T')[0],
          ['orderDetail.payWay']:res.data.payWay,
          ['orderDetail.goodsList']:goodsList,
          actualPriceShow: true,
        })
      }
    })
  },
  //待发货，已发货、待付款订单详情
  getDetailByState(orderId){
    let that = this
    let data = {
      orderId
    }
    let goodsList = []
    console.log(data)
    app.request('wx_app/agent_order/detailByState',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        res.data.orderDetails.forEach(item=>{
          goodsList.push({
            name: item.name,
            url: item.pic,
            num: item.amount,
            price: item.price==0?"线下商议":item.price,
            type: item.versionValues,
            orderDetailId:item.stockSkuId,
            productId:item.productId,
            productType:item.productType,
            refundStatus: item.isApplyReturns==1?1:0,
            color:item.tagColor,
            companyName:item.productTag,
            orderDetailId:item.orderDetailId
          })
          if (item.price==0) {
            item.orderPrice=0
          }
        })
        this.setData({
          ['addressInfo.name']:res.data.consignee,
          ['addressInfo.address']:res.data.address,
          ['addressInfo.phone']:res.data.consignee_phone,
          ['orderDetail.orderNo']:res.data.orderNo,
          ['orderDetail.goodsPrice']:res.data.orderPrice==0?"线下商议":res.data.orderPrice,
          ['orderDetail.downTime']:res.data.createTime.split('T')[0],
          ['orderDetail.logisticsType']:res.data.logisticsType,
          ['orderDetail.logisticsPhone']:res.data.logisticsPhone,
          ['orderDetail.logisticsTime']:res.data.logisticsTime,
          ['orderDetail.logisticsDesc']:res.data.logisticsDesc,
          ['orderDetail.goodsList']:goodsList,
          ['orderDetail.freight']:res.data.deliveryFee,
          ['orderDetail.deliveryTime']:res.data.deliveryTime,
          ['orderDetail.manufacturerId']:res.data.manufacturerId,
          ['orderDetail.createAccountName']:res.data.createAccountName,
          ['orderDetail.payableOrNot']:res.data.payableOrNot,
          ['orderDetail.payWay']:res.data.payWay
        })
        //物流信息
        if (res.data.logisticsType==='第三方物流') {
          this.logisticsDetail(that.data.orderId)
        }else if (res.data.logisticsType==='卖家配送') {
          this.firmsLogisticsDetail(res.data.logisticsPhone,res.data.logisticsTime,res.data.deliveryTime)
        }else{
          this.selfLogisticsDetail(res.data.logisticsTime,res.data.deliveryTime)
        }
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //取消订单
  cancelOrder(){
    let data = {
      orderId:this.data.orderId
    }
    console.log(data)
    app.request('wx_app/agent_order/cancelWaitDeliverOrder',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        wx.showToast({
          title:'取消成功',
          success(){
            setTimeout(function(){
              wx.switchTab({
                url:'../my'
              })
            },1000)
          }
        })
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //删除订单
  deletOrder(){
    let data = {
      orderId:this.data.orderId
    }
    app.request('wx_app/agent_order/del',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        wx.showModal({
          title:'删除订单',
          content:'确定要删除订单吗？',
          success: function(res) {
            if (res.confirm) {
              wx.showToast({
                title:'删除成功',
                success(){
                  setTimeout(function(){
                    wx.switchTab({
                      url:'../my'
                    })
                  },1000)
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  // bindPay(){
  //   let data = {
  //     orderId:this.data.orderId
  //   }
  //   if (this.data.orderDetail.payWay=='微信扫码支付') {
  //     app.request('wx_app/pay/qr_url',data,'GET').then(res=>{
  //       if (res.message=='成功') {
  //         wx.navigateTo({
  //           url:'../../stock/scanCode?url='+res.data+'&price='+this.data.orderDetail.goodsPrice
  //         })
  //       }else{
  //         app.errorMsg(res.message)
  //       }
  //     })
  //   }else{
  //     wx.showModal({
  //       title: '确认线下结算',
  //       content: '确定客户已经结算了吗?',
  //       success: function(res) {
  //         if (res.confirm) {
  //           app.request('wx_app/pay/underLine/finish',data,'GET').then(res=>{
  //             console.log(res)
  //             if (res.code==1) {
  //               wx.switchTab({
  //                 url:'../my'
  //               })
  //             }else{
  //               app.errorMsg(res.message)
  //             }
  //           })
  //         } else if (res.cancel) {
  //           console.log('用户点击取消')
  //         }
  //       }
  //     })
  //   }
  // }
  bindPay(){
    wx.navigateTo({
      url:'../../stock/orderDetail?orderId='+this.data.orderId
    })
  },
  //配送详情(第三方物流)
  logisticsDetail(orderId){

    let data = {
      orderId
    }
    console.log(data)
    app.request('wx_app/logistics/inquiryLogistics',data,'GET').then(res=>{
      console.log(res)

      if (res.code==1) {
        if (res.data.Success) {
          let length = res.data.Traces.length
          console.log()
          this.setData({
            ['logisticsList[0].info']:res.data.Traces[length-1].AcceptStation,
            ['logisticsList[0].time']:res.data.Traces[length-1].AcceptTime,
            ['logisticsList[0].isNew']:true,
            ['logisticsList[0].isLast']:false,
          })
        }else{
          app.errorMsg('没有物流信息')
        }
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //配送详情（厂家配送）
  firmsLogisticsDetail(logisticsPhone,logisticsTime,deliveryTime){
    let type = this.data.orderType
    console.log(type)
    if (type==3) { //货在路上
      this.setData({
        ['logisticsList[0].info']:"货运已出发，请内心等待。联系电话"+logisticsPhone,
        ['logisticsList[0].time']:deliveryTime,
        ['logisticsList[0].isNew']:true,
        ['logisticsList[0].isLast']:false,
      })
    }else if (type==4) { //货已经收到
      this.setData({
        ['logisticsList[0].info']:"货已到店，本次配送完成，感谢您此次购买，祝您生活愉快！",
        ['logisticsList[0].time']:logisticsTime,
        ['logisticsList[0].isNew']:true,
        ['logisticsList[0].isLast']:false,
      })
    }
  },
  //自提信息
  selfLogisticsDetail(logisticsTime,deliveryTime){
    let type = this.data.orderType
    if (type==3) { //货在路上
      this.setData({
        ['logisticsList[0].info']:"",
        ['logisticsList[0].time']:deliveryTime,
        ['logisticsList[0].isNew']:true,
        ['logisticsList[0].isLast']:false,
      })
    }else if (type==4) { //货已经收到
      this.setData({
        ['logisticsList[0].info']:"您已到店自提，感谢您此次购买，祝您生活愉快!",
        ['logisticsList[0].time']:logisticsTime,
        ['logisticsList[0].isNew']:true,
        ['logisticsList[0].isLast']:false,
      })
    }
  },
  //填写凭证信息
  bindVoucher(){
    wx.navigateTo({
      url:'voucher?orderId='+this.data.orderId
    })

  },
  //查看凭证信息
  checkVoucher(){
    wx.navigateTo({
      url:'checkVoucher?orderId='+this.data.orderId
    })
  },
  //检测是否有凭证
  monitorVoucher(orderId){
    let that = this
    let data = {
      orderId
    }
    app.request('wx_app/user_order/getVoucher',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        if (res.data.buyerName===null||res.data.buyerPhone===null) {
          that.setData({
            voucher:false
          })
        }else{
          that.setData({
            voucher:true
          })
        }
      }
    })
  },
  //确认收货
  bindConfirmReceipt(){
    var that = this
    let data = {
      orderId:this.data.orderId
    }
    app.request('wx_app/agent_order/confirmReceipt',data,'GET').then(res=>{
      if (res.code==1) {
        wx.showToast({
          icon:'success',
          title:'确认收货成功'
        })
        that.setData({
          '[orderDetail.orderStatus]':4
        })
        that.getDetailByState(that.data.orderId)
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //付款 2018-12-14添加
  payUnderLine(){
    var that = this
    let data = {
      orderId:this.data.orderId
    }
    wx.showModal({
      title: '确认线下结算',
      content: '确定客户已经结算了吗?',
      success: function(res) {
        if (res.confirm) {
          app.request('wx_app/pay/underLine/finish',data,'GET').then(res=>{
            console.log(res)
            if (res.code==1) {
              wx.switchTab({
                url:'../my'
              })
            }else{
              app.errorMsg(res.message)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
          app.request('wx_app/pay/underLine/cancel',data,'GET').then(res=>{
            console.log(res)

          })
        }
      }
    })
  },
  getPayCode(orderId){
    var that = this
    let data = {
      orderId
    }
    console.log(data)
    app.request('wx_app/pay/qr_url',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        this.setData({
          payCode:res.data
        })
        // let price = this.data.newTotalPrice - this.data.oldTotalPrice
        // wx.navigateTo({
        //   url:'../../stock/scanCode?url='+res.data+'&price='+price
        // })
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  bindLookCode(){
    let that = this
    this.setData({
      isScanCode:true
    })
    wx.getUserInfo({
      success(res){
        console.log(res.userInfo)
        that.setData({
          nickName:res.userInfo.nickName,
          avatarUrl:res.userInfo.avatarUrl
        })
      }
    })
  },
  quit(){
    this.setData({
      isScanCode:false
    })
  },
  //立即付款
  bindNowPay(e){
    let orderId = e.currentTarget.dataset.orderId
    let applyType = e.currentTarget.dataset.applyType
    wx.navigateTo({
      url:'../purchase/confirmOrder?orderId='+orderId+'&applyType='+applyType
    })
  }
})
